<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/11/21
 * Time: 15:56
 */

namespace app\common\model;


use library\v163Class;
use think\Cache;
use think\cache\Driver;
use think\Model;

/**
 * 网易终端用户
 *
 * Class NeteaseUser
 * @package app\common\model
 *
 * @property integer uid
 * @property string vod_token
 * @property string created
 */
class NeteaseUser extends Model
{
    protected $table = 'netease_user';
    protected $pk = 'uid';

    /**
     * 获取注册用户
     *
     * @param $uid
     * @return array
     */
    public static function getUser($uid) {

        $nu = self::get($uid);
        if (empty($nu)) {
            $token = md5(time().mt_rand(10000, 999999));
            $re = self::setVodUser($uid, $token);
            $nu = self::create([
                'uid' => $uid,
                'vod_accid' => $re['accid'],
                'vod_token' => $re['token'],
            ]);
        }
        return [
            'accid' => $nu['vod_accid'],
            'token' => $nu['vod_token'],
        ];
    }

    const DEFAULT_USER_ID = 0;
    const DEFAULT_USER_TOKEN = 'asdfghjkl;';
    public static function defaultToken() {
        return md5(self::DEFAULT_USER_TOKEN);
    }
    /**
     * 获取默认的用户
     *
     * @return array
     */
    public static function defaultUser() {

        $accid = v163Class::generateAccId(self::DEFAULT_USER_ID);
        $token = self::defaultToken();

        return [
            'accid' => $accid,
            'token' => $token,
        ];
    }

    public static function setVodUser($uid, $token) {
        try{
            $re = v163Class::getInstance()->vod_user_create($uid, $token);
        }catch (\Exception $ex){
            $re = v163Class::getInstance()->vod_user_update($uid, $token);
        }
        return $re;
    }

    private static function cacheToken() : Driver {
        return Cache::tag('NeteaseUser')->tag('token');
    }
}